package com.example.airoles.service;

import com.example.airoles.config.RoleConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class RoleRecommendationService {
    
    @Autowired
    private RoleConfig roleConfig;
    
    // Keywords mapping for different problem types
    private final Map<String, List<String>> problemTypeKeywords = Map.of(
        "life_direction", Arrays.asList("confused", "lost", "purpose", "direction", "meaning", "future", "career", "goals"),
        "relationships", Arrays.asList("relationship", "love", "family", "friends", "conflict", "communication", "trust"),
        "emotional_support", Arrays.asList("sad", "depressed", "anxious", "stress", "overwhelmed", "lonely", "grief", "angry"),
        "personal_growth", Arrays.asList("growth", "improvement", "learning", "skills", "confidence", "self-esteem", "habits"),
        "decision_making", Arrays.asList("decision", "choose", "options", "dilemma", "choice", "unsure", "pros", "cons"),
        "philosophical", Arrays.asList("philosophy", "existence", "truth", "reality", "beliefs", "values", "spiritual", "wisdom")
    );
    
    // Role recommendations based on problem types  
    private final Map<String, List<String>> problemTypeToRoles = Map.of(
        "life_direction", Arrays.asList("life_coach", "wise_mentor", "philosopher"),
        "relationships", Arrays.asList("therapist", "wise_mentor", "life_coach"),
        "emotional_support", Arrays.asList("therapist", "wise_mentor", "harry"),
        "personal_growth", Arrays.asList("life_coach", "philosopher", "socrates"),
        "decision_making", Arrays.asList("life_coach", "socrates", "wise_mentor"),
        "philosophical", Arrays.asList("philosopher", "socrates", "wise_mentor")
    );
    
    // Skills recommendations based on problem types
    private final Map<String, List<String>> problemTypeToSkills = Map.of(
        "life_direction", Arrays.asList("value_clarification", "goal_setting", "perspective_shift"),
        "relationships", Arrays.asList("emotion_processing", "active_listening", "cognitive_reframe"),
        "emotional_support", Arrays.asList("emotion_processing", "active_listening", "mindfulness_guidance"),
        "personal_growth", Arrays.asList("strength_discovery", "growth_mindset", "goal_setting"),
        "decision_making", Arrays.asList("decision_matrix", "value_clarification", "perspective_shift"),
        "philosophical", Arrays.asList("socratic", "perspective_shift", "value_clarification")
    );
    
    public RoleRecommendation recommendRole(String userMessage) {
        String problemType = identifyProblemType(userMessage.toLowerCase());
        
        List<String> recommendedRoles = problemTypeToRoles.getOrDefault(problemType, 
            Arrays.asList("life_coach", "wise_mentor"));
        List<String> recommendedSkills = problemTypeToSkills.getOrDefault(problemType,
            Arrays.asList("active_listening", "perspective_shift"));
            
        return new RoleRecommendation(problemType, recommendedRoles, recommendedSkills);
    }
    
    public List<RoleInfo> searchRoles(String query) {
        String lowerQuery = query.toLowerCase();
        
        return roleConfig.roleSystemPrompts.entrySet().stream()
            .filter(entry -> entry.getKey().contains(lowerQuery) || 
                           entry.getValue().toLowerCase().contains(lowerQuery))
            .map(entry -> new RoleInfo(entry.getKey(), entry.getValue(), 
                getRoleCategories(entry.getKey())))
            .collect(Collectors.toList());
    }
    
    public List<RoleInfo> getRolesByCategory(String category) {
        Map<String, List<String>> categories = Map.of(
            "guidance", Arrays.asList("life_coach", "wise_mentor", "therapist"),
            "philosophical", Arrays.asList("philosopher", "socrates"),
            "creative", Arrays.asList("harry"),
            "professional", Arrays.asList("interviewer")
        );
        
        List<String> roleIds = categories.getOrDefault(category, new ArrayList<>());
        
        return roleIds.stream()
            .filter(roleId -> roleConfig.roleSystemPrompts.containsKey(roleId))
            .map(roleId -> new RoleInfo(roleId, 
                roleConfig.roleSystemPrompts.get(roleId),
                Arrays.asList(category)))
            .collect(Collectors.toList());
    }
    
    private String identifyProblemType(String message) {
        Map<String, Integer> scores = new HashMap<>();
        
        for (Map.Entry<String, List<String>> entry : problemTypeKeywords.entrySet()) {
            int score = 0;
            for (String keyword : entry.getValue()) {
                if (message.contains(keyword)) {
                    score++;
                }
            }
            scores.put(entry.getKey(), score);
        }
        
        return scores.entrySet().stream()
            .max(Map.Entry.comparingByValue())
            .map(Map.Entry::getKey)
            .orElse("general");
    }
    
    private List<String> getRoleCategories(String roleId) {
        // Simple category mapping
        Map<String, String> roleToCategory = Map.of(
            "life_coach", "guidance",
            "wise_mentor", "guidance", 
            "therapist", "guidance",
            "philosopher", "philosophical",
            "socrates", "philosophical",
            "harry", "creative",
            "interviewer", "professional"
        );
        
        String category = roleToCategory.getOrDefault(roleId, "general");
        return Arrays.asList(category);
    }
    
    public static class RoleRecommendation {
        public String problemType;
        public List<String> recommendedRoles;
        public List<String> recommendedSkills;
        public String explanation;
        
        public RoleRecommendation(String problemType, List<String> roles, List<String> skills) {
            this.problemType = problemType;
            this.recommendedRoles = roles;
            this.recommendedSkills = skills;
            this.explanation = generateExplanation(problemType);
        }
        
        private String generateExplanation(String problemType) {
            Map<String, String> explanations = Map.of(
                "life_direction", "Based on your message, you seem to be seeking direction and purpose. I recommend life coaching approaches.",
                "relationships", "It appears you're dealing with relationship challenges. Therapeutic and mentoring approaches might help.",
                "emotional_support", "You seem to need emotional support and understanding. Empathetic roles would be most beneficial.",
                "personal_growth", "Your message suggests a focus on self-improvement. Growth-oriented coaching approaches are recommended.",
                "decision_making", "You appear to be facing important decisions. Structured decision-making approaches would be helpful.",
                "philosophical", "Your inquiry touches on deeper philosophical questions. Philosophical and Socratic approaches are recommended."
            );
            
            return explanations.getOrDefault(problemType, "Based on your message, I recommend starting with a general life coaching approach.");
        }
    }
    
    public static class RoleInfo {
        public String roleId;
        public String description;
        public List<String> categories;
        
        public RoleInfo(String roleId, String description, List<String> categories) {
            this.roleId = roleId;
            this.description = description;
            this.categories = categories;
        }
    }
}